# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging,sys,threading,time
from piHAlibs import (coroutine,broadcast,printer)

logger = logging.getLogger()

if sys.hexversion > 0x030000F0:
    import queue as Queue
else:
    import Queue

INPUTq = Queue.Queue()
ERRMSGq = Queue.Queue()
MESSAGEq = Queue.Queue()
QEmpty = Queue.Empty
PortInUse = {}
SetupControllers = {}
SetupDaemons= {}
TXControllers = {}


class INPUTPARSER(object):
    def __init__(self,arg=None):
        self.stop = False
        self.type = 'SRV'
        self.name = 'INParser'
        self.servercmds = {'STARTB':self.startb,'STARTS':self.starts,'STOPS':self.stops}
        self.Functions = {}
        self.featurenames = ['PRINTER']
        self.features = [printer()]

    def tsetup(self):
        self.setup = True

    def preparse(self,data):
        if isinstance(data,list):
            items = data
        else:
            items = data.split()
        #Pre - parsing first item
        fct = items[0].upper()
        logger.debug("Pre - parsing first item function : %s ", fct)
        if fct in self.Functions:
            res = self.Functions[fct](data)
            logger.debug("Result after pre parsing : %s", repr(res))
        else:
            logger.debug("Function %s unknown for InputParser", fct)


    def bcasterr(self):
        while not self.stop:
            try:
                a = ERRMSGq.get_nowait()
                logger.debug("Getting error message %s from error msg queue", repr(a))
                if isinstance(a,list):
                    msg = ' '.join(a)
                else:
                    msg = a
                broadcast(self.features).send(msg)
            except QEmpty:
                time.sleep(1)

    def bcastmsg(self):
        while not self.stop:
            try:
                a = MESSAGEq.get_nowait()
                logger.debug("Getting message %s from msg queue", repr(a))
                if isinstance(a,list):
                    msg = ' '.join(a)
                else:
                    msg = a
                broadcast(self.features).send(msg)
            except QEmpty:
                time.sleep(1)

    def serve(self):
        while not self.stop:
            try:
                data = INPUTq.get_nowait()
                logger.debug("Getting data %s from input queue", data)
                if data != '': self.preparse(data)
            except QEmpty:
                time.sleep(1)

    def startb(self):
        tt = threading.Thread(target=self.bcasterr)
        tt.name = 'BCASTERRS'
        tt.daemon = True
        tt.start()
        print ('BCASERRS started and active...')
        tt = threading.Thread(target=self.bcastmsg)
        tt.name = 'BCASTMSGS'
        tt.daemon = True
        tt.start()
        print ('BCASTMSGS started and active...')

    def starts(self):
        tt = threading.Thread(target=self.serve)
        tt.name = self.name
        tt.daemon = True
        tt.start()
        print ('INPUTPARSER started and active...')

    def stops(self):
        self.stop = True
        print ('INPUTPARSER and BCASTMSGS shutting down...')

